package com.server.view;

import com.common.User;
import com.server.entity.DataBuffer;
import com.server.model.ServerAccepter;
import com.server.model.UserService;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

/***新的服务端窗口，可以看到已注册用户和在线用户
 *
 */
public class newServerFrame extends JFrame{
    private static final long serialVersionUID = 6274443611957724780L;
    private JTextField jta_msg;
    private JTable onlineUserTable ;
    private JTable registerUserTable ;

    ServerAccepter serverAccepter;
    Thread thread;
    public newServerFrame() throws Exception {
        thread = new Thread(() -> serverAccepter = new ServerAccepter());
        thread.start();
        init();
        //数据加载
        loadLoginData();
        loadData();
        //窗体可视化
        setVisible(true);
    }

    //把所有已注册的用户信息加载到RegistedUserTableModel中
    private void loadData() throws Exception {
        List<User> users=new UserService().loadAllUser();
        for (User user : users) {
            DataBuffer.registedUserTableModel.add(new String[]{
                    user.getId(),
                    user.getPwd(),
                    user.getUsername(),
                    user.getSex()
            });
        }
    }

    //将所有登录的用户加载到onlineUserTable上
    private void loadLoginData()throws Exception{
        List<User> users=new UserService().loginUser();
        for(User user:users){
            DataBuffer.onlineUserTableModel.add(new String[]{
                    user.getId(),
                    user.getUsername(),
                    user.getSex()
            });
        }
    }

    //窗体初始化函数
    public void init(){
        this.setTitle("Gdufe服务器");
        //使界面在屏幕中央
        setBounds(((Toolkit.getDefaultToolkit().getScreenSize().width)/2)-300,
                ((Toolkit.getDefaultToolkit().getScreenSize().height)/2)-300,
                700,475);

        JPanel panel = new JPanel();
        Border border = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
        panel.setBorder(BorderFactory.createTitledBorder(border,
                "服务器监控", TitledBorder.LEFT,TitledBorder.TOP));
        this.add(panel, BorderLayout.NORTH);

        JLabel label = new JLabel("服务器端口: ");
        panel.add(label);
        JButton exitBtn = new JButton("关闭服务器");//关闭关闭服务器按钮
        panel.add(exitBtn);
        JLabel ip_msg = new JLabel("当前局域网ip:");
        panel.add(ip_msg);

        //文本框显示当前ip地址：
        jta_msg = new JTextField(30);
        panel.add(jta_msg);

        //刷新按钮，刷新服务器在线人数
        JButton bu_reload=new JButton("刷新");
        panel.add(bu_reload);

        bu_reload.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //载入数据(将注册的信息载入状态表)
                try {
                    //数据重新加载(仅重新加在在线用户)
                    removeData();
                    loadLoginData();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });

        //使用服务器缓存中的TableModel
        onlineUserTable=new JTable(DataBuffer.onlineUserTableModel);
        registerUserTable=new JTable(DataBuffer.registedUserTableModel);

        //选项卡
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("在线用户列表", new JScrollPane(onlineUserTable));
        tabbedPane.addTab("已注册用户列表", new JScrollPane(registerUserTable));
        tabbedPane.setTabComponentAt(0, new JLabel("在线用户列表"));
        this.add(tabbedPane, BorderLayout.CENTER);


        final JLabel stateBar = new JLabel("", SwingConstants.RIGHT);
        stateBar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
        //用定时任务来显示当前时间
        new java.util.Timer().scheduleAtFixedRate(
                new TimerTask(){
                    DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    public void run() {
                        stateBar.setText("当前时间：" + df.format(new Date()) + "  ");
                    }
                }, 0, 1000);
        this.add(stateBar, BorderLayout.SOUTH); //把状态栏添加到窗体的南边


        //关闭窗口
        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                logout();
            }
        });

        /* 添加关闭服务器按钮事件处理方法 */
        exitBtn.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent event) {
                logout();
            }
        });
    }

    //退出服务器函数（需要确认）
    /** 关闭服务器 */
    private void logout() {
        int select = JOptionPane.showConfirmDialog(newServerFrame.this,
                "确定关闭吗？\n\n关闭服务器将中断与所有客户端的连接!",
                "关闭服务器",
                JOptionPane.YES_NO_OPTION);
        //如果用户点击的是关闭服务器按钮时会提示是否确认关闭。
        if (select == JOptionPane.YES_OPTION) {
            System.exit(0);//退出系统
        }else{
            //覆盖默认的窗口关闭事件动作
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        }
    }

    //清空列表数据
    private void removeData() throws Exception {
//        List<User> users=new UserService().loadAllUser();
//        for (User user : users) {
//            DataBuffer.onlineUserTableModel.remove(user.getId());
//        }
        //更新数据库isLogin

        DataBuffer.onlineUserTableModel.removeAll();
    }
}
